/**
 * Normal bir formu kolayca ajax forma dönüştüren bir jQuery Eklentisidir.
 * 
 * @author Ali OYGUR <alioygur@gmail.com>
 * @version 1.0 Beta
 */

(function($) {
	
	// Global Vars
	var formAction, formId, FORM;
	
	$.fn.aliAjaxForm = function(options) 
	{
		// set global vars
		FORM = $(this);
		formId = FORM.prop('id');
		formAction = FORM.prop('action');
		
		var methods = {
			init: function() {	
				jQuery('form#' + formId).hide();
			    jQuery('#error').remove();
			    jQuery('#loading').remove();
			    jQuery('#success').remove();
			    jQuery('form#' + formId).before('<div class="notification loading" id="loading">&nbsp;</div>');
			},
			ajaxSuccess: function(response, textStatus, jqXHR) {
				
				jQuery('#loading').remove();
				
				// if there is an error
				if(response.error === true) {
					
					jQuery('form#' + formId).before('<div class="notification error" id="error">' + response.msg + '</div>');
	            	jQuery('form#' + formId).show();
	            	jQuery.colorbox.resize();
	            	
				} else {
					
					// Costum success
					switch (formId) {
						
						case 'xxx':
						
			                return true;
							break;
						
						default:
						
			                // eğer karşıdan herhangi bir redirect url belirtilmişse o adrese gitsin
			                if(response.redirect) {
			                	
			                	window.location.href = response.redirect
			                	return true;
			                	
			                } else {
						                	
								jQuery('form#' + formId).before('<div class="notification success" id="success">' + response.msg + '</div>');
				            	jQuery('form#' + formId).show();
				            	jQuery.colorbox.resize();           	
			                }
			                
			                return true;
							break;
					}
					
				}				
			}
		}
		
		// Initialize
		methods.init();
		
		$.ajax({
			type: 'POST',
			url: formAction,
			dataType: 'json',
			data: this.serialize(),
			success: methods.ajaxSuccess
		});
	}
	
})(jQuery);